package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.CreateStudentDTO;
import com.sky.dto.UpdateStudentDTO;
import com.sky.dto.UpdateStudentPasswordDTO;
import com.sky.entity.Student;
import com.sky.mapper.StudentMapper;
import com.sky.service.StudentService;
import com.sky.vo.StudentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import com.sky.entity.Address;
import com.sky.mapper.AddressMapper;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Override
    public IPage<StudentVO> getStudentList(IPage<Student> page, String username, String studentId, String status) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (studentId != null && !studentId.isEmpty()) {
            queryWrapper.like("student_id", studentId);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }
        IPage<Student> studentPage = baseMapper.selectPage(page, queryWrapper);
        // 转换为VO
        return studentPage.convert(student -> {
            StudentVO studentVO = new StudentVO();
            BeanUtils.copyProperties(student, studentVO);
            return studentVO;
        });
    }

    @Override
    public StudentVO getStudentById(Long id) {
        Student student = baseMapper.selectById(id);
        if (student == null) {
            return null;
        }
        StudentVO studentVO = new StudentVO();
        BeanUtils.copyProperties(student, studentVO);
        return studentVO;
    }

    @Override
    public Long createStudent(CreateStudentDTO createStudentDTO) {
        // 检查学号是否已存在
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", createStudentDTO.getStudentId());
        Student existingStudent = baseMapper.selectOne(queryWrapper);
        if (existingStudent != null) {
            throw new RuntimeException("学号已存在");
        }
        
        Student student = new Student();
        BeanUtils.copyProperties(createStudentDTO, student);
        // 加密密码
        student.setPassword(DigestUtils.md5DigestAsHex(student.getPassword().getBytes()));
        student.setStatus("active");
        student.setTotalOrders(0);
        student.setTotalAmount(new java.math.BigDecimal(0));
        baseMapper.insert(student);
        return student.getId();
    }

    @Override
    public void updateStudent(UpdateStudentDTO updateStudentDTO) {
        Student student = new Student();
        BeanUtils.copyProperties(updateStudentDTO, student);
        baseMapper.updateById(student);
    }

    @Autowired
    private AddressMapper addressMapper;

    @Transactional
    @Override
    public void deleteStudent(Long id) {
        // 1. 查询该学生的所有地址
        List<Address> addresses = addressMapper.selectByStudentId(id);
        // 2. 删除该学生的所有地址
        if (addresses != null && !addresses.isEmpty()) {
            for (Address address : addresses) {
                addressMapper.deleteById(address.getId());
            }
        }
        // 3. 删除学生
        baseMapper.deleteById(id);
    }

    @Override
    public void toggleStudentStatus(Long id) {
        Student student = baseMapper.selectById(id);
        if (student != null) {
            student.setStatus(student.getStatus().equals("active") ? "inactive" : "active");
            baseMapper.updateById(student);
        }
    }

    @Override
    public void updateStudentPassword(UpdateStudentPasswordDTO updateStudentPasswordDTO) {
        Student student = baseMapper.selectById(updateStudentPasswordDTO.getId());
        if (student != null) {
            // 验证旧密码
            String oldPasswordMd5 = DigestUtils.md5DigestAsHex(updateStudentPasswordDTO.getOldPassword().getBytes());
            if (oldPasswordMd5.equals(student.getPassword())) {
                // 设置新密码
                student.setPassword(DigestUtils.md5DigestAsHex(updateStudentPasswordDTO.getNewPassword().getBytes()));
                baseMapper.updateById(student);
            } else {
                throw new RuntimeException("旧密码不正确");
            }
        }
    }
}